<template>
  <div class="flex-column">
    <div class="flex justify-between flex-row-reverse">
      <div class="text-right flex justify-end flex-wrap ">
        <el-select
          v-model="stationType"
          clearable
          style="width: 150px"
          class=" mb-10"
          :placeholder="$t('SELECT_STATION')"
          @change="selectedIds = []"
        >
          <el-option value="no" :label="$t('NOT_A_Z')" />
          <el-option value="a" :label="$t('TRANS_DIRECT_START')" />
          <el-option value="z" :label="$t('TRANS_DIRECT_END')" />
        </el-select>
        <!-- 全部区域 -->
        <region-cascader
          v-show="stationType == 'no' || stationType == ''"
          style="width: 280px"
          class="ml-10 mb-10"
          :multiple="true"
          :selected-ids="selectedIds"
          @change="stationChange"
        />
        <!-- A端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          style="width: 280px"
          class="ml-10 mb-10"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'A_END_STATION_NAME' : 'Z_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? aStationChange(val) : zStationChange(val)
            }
          "
        />
        <!-- Z端站点 -->
        <region-cascader
          v-show="stationType === 'a' || stationType === 'z'"
          class="ml-10 mb-10"
          style="width: 280px"
          :selected-ids="selectedIds"
          :placeholder="stationType === 'a' ? 'Z_END_STATION_NAME' : 'A_END_STATION_NAME'"
          :multiple="true"
          @change="
            val => {
              stationType === 'a' ? zStationChange(val) : aStationChange(val)
            }
          "
        />
        <el-input
          v-model.trim="queryData.keyword"
          style="width: 200px"
          class="mb-10 ml-10"
          maxlength="32"
          clearable
          :placeholder="`${$t('ENTER_CABLE_NAME')}/${$t('RESOURCE_CODE')}`"
          @keyup.enter.native="$debounce(search)"
        />
        <!-- 占位用 -->
        <div v-show="stationType == 'no' || stationType == ''" style="width: 280px;" />
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{
          $t('QUERY')
        }}</el-button>
      </div>
      <div class="flex mb-10">
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD_OPTICAL_CABLE')
        }}</el-button>
        <el-button
          v-if="permission.import"
          type="primary"
          icon="el-icon-upload2"
          @click="importVisible = true"
        >{{ $t('IMPORT') }}</el-button>
        <el-button
          v-if="permission.lengthcheck"
          type="primary"
          icon="el-icon-setting"
          @click="lengthCheckVisible = true"
        >{{ $t('LENGTH_CHECK_CONFIG') }}</el-button>
        <!-- <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportClick"
        >{{ $t('EXPORT') }}</el-button> -->
      </div>
    </div>
    <TableView
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="resetSize(250)"
      @operate="operate"
      @pageChange="pageChange"
    />
    <edit :visible="editShow" :type="operateType" :data="rowData" @close="closeEdit" @reload="reload" />
    <opticalCable :visible="portInfoVisible" :row-data="rowData" @close="portInfoVisible = false" />
    <!--导入引导-->
    <ConfImportDialog
      :visible="importVisible"
      template-url="template/光缆批量导入模板.xlsx"
      import-url="/import/importCable"
      service-name="oen"
      import-tips="CABLE_IMPORT_TIPS"
      @close="closeEdit"
    />
    <LengthCheckConfig :visible.sync="lengthCheckVisible" />
    <!--编辑光缆段-->
    <EditCable :visible="editcableShow" :row-data="rowData" :type="operateType" :cable-list="rowCableList" @close="closeEdit" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import OpticalCable from './OpticalCable'
  import cableApi from '@/api/oen/CableApi'
  import cableSegmentApi from '@/api/oen/CableSegmentApi'
  import facilityApi from '@/api/oen/FacilityApi'
  import { downloadFile, changeDecimal, getParentsById } from '@/utils/common'
  import RegionCascader from '@/components/RegionCascader'
  import Edit from './Edit'
  import TableView from '@/components/TableView'
  import ConfImportDialog from '@/components/ConfImportDialog'
  import LengthCheckConfig from './LengthCheckConfig'
  import EditCable from './EditCable'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'ConfCablePage',
    components: {
      Edit,
      RegionCascader,
      OpticalCable,
      TableView,
      ConfImportDialog,
      LengthCheckConfig,
      EditCable
    },
    data() {
      return {
        lengthCheckVisible: false,
        portInfoVisible: false,
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        queryData: {
          keyword: '',
          startStationIdList: [],
          endStationIdList: [],
          stationIdList: []
        },
        selectedIds: [],
        stationType: '',
        importVisible: false,
        tableData: [],
        rowData: {},
        operateType: 'add',
        editShow: false,
        tableHeader: [
          {
            label: 'CABLE_NAME',
            prop: 'cableName',
            width: '250',
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'A_END_REGIONAL_STATION_NAME',
            prop: 'startStationName',
            width: '250'
          },
          {
            label: 'A_END_ROOM_NAME',
            prop: 'startRoomName',
            configType: 'extend',
            width: '250'
          },
          {
            label: 'Z_END_REGIONAL_STATION_NAME',
            prop: 'endStationName',
            width: '250'
          },
          {
            label: 'Z_END_ROOM_NAME',
            prop: 'endRoomName',
            configType: 'extend',
            width: '250'
          },
          {
            label: 'CABLE_LEVEL',
            prop: 'cableLevelText',
            width: '150'
          },
          {
            label: 'CABLE_TYPE',
            prop: 'cableTypeText',
            width: '150'
          },
          {
            label: 'CABLE_MODEL',
            prop: 'model',
            configType: 'extend',
            width: '150'
          },
          {
            label: 'CABLE_SPE',
            prop: 'cableNormText',
            width: '150'
          },
          {
            label: 'FIBER_CORE_TYPE',
            prop: 'fiberTypeText',
            width: '150'
          },
          {
            label: 'CABLE_LENGTH',
            prop: 'cableLength',
            width: '130'
          },
          {
            label: 'NOMINAL_CAPACITY',
            prop: 'capacity',
            width: '150'
          },
          {
            label: 'NUMBER_CONNECTED',
            prop: 'connNum',
            configType: 'extend',
            width: '150'
          },
          {
            label: 'NUMBER_TAKEUP',
            prop: 'occupyNum',
            configType: 'extend',
            width: '150'
          },
          {
            label: 'NUMBER_IDLE',
            prop: 'idleNum',
            configType: 'extend',
            width: '150'
          },
          {
            label: 'RESOURCE_CODE',
            prop: 'resourceCode',
            tips: 'RESOURCE_CODE_TIPS',
            width: '150'
          },
          {
            label: 'VENDOR',
            prop: 'company',
            configType: 'extend',
            width: '150'
          },
          {
            label: 'BRAND',
            prop: 'brand',
            configType: 'extend'
          }
        ],
        editCablePathShow: false,
        editcableShow: false,
        cablePlaceList: [], // 所有光缆段列表
        facilityList: [], // 设施列表
        rowCableList: [], // 当前选中光缆光缆段
        functionName: 'cable'
      }
    },
    provide() {
      return {
        parentVM: this
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'baseRegionList', 'customDictMap', 'stationTree']),
      permission() {
        return this.$store.getters.getAuthData('conf:cable')
      }
    },
    activated() {
      this.loadData()
      this.getCableList()
    },
    methods: {
      async getCableList() { // 获取所有光缆段
        try {
          const cables = await cableSegmentApi.list()
          const facilitys = await facilityApi.list()
          this.facilityList = facilitys
          const list = cables.sort((a, b) => a.sort - b.sort) || []
          this.cablePlaceList = list
        } catch (e) { console.log(e) }
      },
      loadData() {
        const queryData = {
          ...searchData,
          ...{ page: this.pageData }
        }
        console.log('queryData', queryData)
        cableApi.queryPage(queryData).then(res => {
          const list = res.list || []
          this.reload(list)
          console.log('this.tableData', this.tableData)
          this.pageData.total = res.total
        })
      },
      reload(list) {
        list = list || this.tableData
        this.tableData = []
        this.tableData = list.map(i => {
          i.startStationName = this.getRegionStationName(i.startStationId)
          i.endStationName = this.getRegionStationName(i.endStationId)
          i.startRoomName = this.getRegionName(i.startRoomId)
          i.endRoomName = this.getRegionName(i.endRoomId)
          i.cableLevelText = this.customDictMap[i.cableLevel.toUpperCase()] || '--'
          i.cableTypeText = this.dictMap.CABLE_TYPE[i.cableType.toUpperCase()] || '--'
          i.cableNormText = this.dictMap.CABLE_NORM[i.cableNorm.toUpperCase()] || '--'
          i.fiberTypeText = this.dictMap.FIBER_TYPE[i.fiberType.toUpperCase()] || '--'
          i.cableLength = changeDecimal(i.cableLength, 3, true)
          i.btns = this.getBtns(i)
          return i
        })
      },
      getBtns(row) {
        const btns = [
          {
            key: 'view',
            show: true,
            label: 'VIEW'
          },
          {
            key: 'mod',
            show: this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'editFibre',
            show: this.permission.fiber,
            label: 'EDIT_FIBRE',
            disabled: row.capacity === 0
          },
          {
            key: 'editCable',
            show: this.permission.path,
            label: 'EDIT_FIBER_CABLE'
          },
          {
            key: 'del',
            show: this.permission.del,
            label: 'DEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      operate(data) {
        switch (data.type) {
        case 'view':
          this.operateType = 'view'
          this.rowData = data.data
          this.editShow = true
          break
        case 'editFibre':
          this.rowData = data.data
          this.portInfoVisible = true
          break
        case 'editCable':
          this.rowData = data.data
          this.operateType = 'edit'
          this.setRowCableList()
          this.editcableShow = true
          break
        case 'mod':
          this.operateType = 'mod'
          this.rowData = data.data
          this.editShow = true
          break
        case 'del':
          this.del(data.data)
          break
        }
      },
      setRowCableList() { // 当前光缆下的光缆段列表 处理开始名称和结束名称
        this.rowCableList = this.cablePlaceList.filter(i => i.cableId === this.rowData.cableId)
        if (this.rowCableList.length) {
          this.rowCableList.forEach(item => {
            item.startPointName = item.startPointType === 'STATION' ? this.getRegionName(item.startPointId)
              : this.facilityList.find(i => i.facilityId === item.startPointId).facilityName
            item.endPointName = item.endPointType === 'STATION' ? this.getRegionName(item.endPointId)
              : this.facilityList.find(i => i.facilityId === item.endPointId).facilityName
          })
        }
        // console.log(this.rowCableList)
      },
      getRegionStationName(regionId) {
        const parents = getParentsById(this.stationTree, regionId, 'regionId') || []
        return parents
          .reverse()
          .map(i => i.regionName)
          .join('/')
      },
      // 获取区域/站点/机房
      getRegionName(stationId) {
        const stationData = this.baseRegionList.find(i => i.regionId === stationId)
        return stationData ? stationData.regionName : ''
      },
      // 区域搜索条件改变
      aStationChange(data) {
        this.queryData.startStationIdList = data
      },
      zStationChange(data) {
        this.queryData.endStationIdList = data
      },
      stationChange(data) {
        this.queryData.stationIdList = data
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        this.queryData.keyword = this.queryData.keyword.trim()
        searchData = {
          ...this.queryData
        }
        this.loadData()
      },
      // 顶部添加
      add() {
        this.operateType = 'add'
        this.rowData = {}
        this.editShow = true
      },
      // 修改
      // 删除
      del(row) {
        this.$confirm(this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('OPTICAL_CABLE'), value: row.cableName }), { type: 'warning' })
          .then(() => {
            cableApi
              .delByCableId({
                cableId: row.cableId,
                cableName: row.cableName
              })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('DELETE_SUCCESS'))
                  this.loadData(true)
                }
              })
          })
          .catch(() => {})
      },
      // 弹窗关闭
      closeEdit(load) {
        this.importVisible = false
        this.editShow = false
        this.editcableShow = false
        if (load === true) {
          this.loadData()
          this.getCableList()
        }
      },
      // 导出文件
      exportClick() {
        const queryData = {
          ...this.queryData,
          ...{ page: this.pageData }
        }
        cableApi.expData(queryData).then(res => {
          downloadFile(res, `${this.$t('NODE_EXPORT_DATA')}.xlsx`)
        })
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      }
    }
  }
</script>
